package com.rpay.service.sms.impl;

import com.rpay.common.dto.sms.SmsCodeDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.enums.SmsCodeEnum;
import com.rpay.common.enums.SmsTypeEnum;
import com.rpay.common.exception.SmsException;
import com.rpay.dao.sms.SmsCodeDao;
import com.rpay.model.sms.SmsCodeDO;
import com.rpay.service.sms.ISmsCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/30
 * @version 1.0
 */
@Service
public class SmsCodeServiceImpl implements ISmsCodeService {
    @Value("${sms.code.invalidTime}")
    private long invalidTime;

    @Autowired
    private SmsCodeDao smsCodeDao;
    @Override
    public SmsCodeDTO getSmsCode(SmsCodeDTO smsCode) {
        SmsCodeDO smsCodeDO = convertSmsCodeDTOToDO(smsCode);
        smsCodeDO = smsCodeDao.select(smsCodeDO);
        SmsCodeDTO smsCodeDTO = convertSmsCodeDOToDTO(smsCodeDO);
        return smsCodeDTO;
    }

    @Override
    public boolean updateValid(Integer id) {
        smsCodeDao.updateValid(id);
        return true;
    }

    private SmsCodeDTO convertSmsCodeDOToDTO(SmsCodeDO smsCodeDO) {
        SmsCodeDTO smsCode = null;
        if (smsCodeDO != null) {
            smsCode = new SmsCodeDTO();
            smsCode.setId(smsCodeDO.getId());
            smsCode.setCode(smsCodeDO.getCode());
            smsCode.setCreateTime(smsCodeDO.getCreateTime());
            smsCode.setReceiver(smsCodeDO.getReceiver());
            smsCode.setType(smsCodeDO.getType());
            smsCode.setVerifyType(smsCodeDO.getVerifyType());
        }
        return smsCode;
    }

    private SmsCodeDO convertSmsCodeDTOToDO(SmsCodeDTO smsCodeDTO) {
        SmsCodeDO smsCode = null;
        if (smsCodeDTO != null) {
            smsCode = new SmsCodeDO();
            smsCode.setType(smsCodeDTO.getType());
            smsCode.setVerifyType(smsCodeDTO.getVerifyType());
            smsCode.setReceiver(smsCodeDTO.getReceiver());
            smsCode.setCode(smsCodeDTO.getCode());
        }
        return smsCode;
    }

    @Override
    public void verifyMail(String verifyType, String email, String code) {
        SmsCodeDO smsCodeDO = new SmsCodeDO();
        smsCodeDO.setVerifyType(verifyType);
        smsCodeDO.setType(SmsTypeEnum.MAIL.getCode());
        smsCodeDO.setReceiver(email);
        smsCodeDO.setCode(code);
        SmsCodeDO smsCode = smsCodeDao.select(smsCodeDO);
        if (smsCode == null) {
            throw new SmsException(PcsResultCode.SMS_CODE_FAIL);
        }
        long failureTime = System.currentTimeMillis() - smsCode.getCreateTime().getTime();
        if (failureTime > invalidTime * 60 * 1000) {
            throw  new SmsException(PcsResultCode.SMS_CODE_EXPIRED);
        }
    }
}
